import { forwardRef, useImperativeHandle, useRef, useState } from 'react';

import { useRequest } from 'ahooks';
import {
  Button,
  Drawer,
  Form,
  FormProps,
  Input,
  InputNumber,
  Select,
  Space,
  TreeSelect
} from 'antd';
import { DataNode } from 'antd/es/tree';

import { store } from '@/store';

import { orgDeptInfoTreeList } from '@/services/base/bumenguanlibumenxiangguanjiekou';
import { orgUserInfoVoPage } from '@/services/base/yonghuguanlixitongyonghujiekou';
import { equInfoAdd, equInfoUpdate } from '@/services/bizApi/shebaoxinxijiekou';
import { ProFormSelect } from '@ant-design/pro-form';

import { BizObject } from './';

type EditOpenBaseArgs = {
  /** 成功回调 */
  onSuccess?: () => void;
};

export type EditRef = {
  open: (
    arg:
      | (EditOpenBaseArgs & {
          type: 'add';
        })
      | (EditOpenBaseArgs & {
          type: 'edit';
          rowData: BizObject;
        })
      | (EditOpenBaseArgs & {
          type: 'detail';
          rowData: BizObject;
        })
  ) => void;
};

export type EditProps = {};

const Edit: React.ForwardRefRenderFunction<EditRef, EditProps> = (_, ref) => {
  const [form] = Form.useForm();
  // 弹窗开启状态
  const [open, setOpen] = useState(false);
  const [args, setArgs] = useState<ArgumentsType<EditRef['open']>[0]>();
  const treeDict = useRef<Record<number, DataNode>>({});
  const tree = useRequest(async () => {
    treeDict.current = {};

    const res = await orgDeptInfoTreeList();

    const formatData = (data: BASE.OrgDeptInfoVo[]): DataNode[] => {
      const result: DataNode[] = [];

      data.forEach((item) => {
        const node: DataNode = {
          title: item.deptName,
          key: item.id!,
          // @ts-ignore
          value: item.id!,
          children: []
        };

        treeDict.current[item.id!] = node;

        if (item.child && item.child.length > 0) {
          node.children = formatData(item.child);
        }

        result.push(node);
      });

      return result;
    };

    return formatData(res.data || []);
  });
  const userInfo = useRequest(
    async () => {
      const res = await orgUserInfoVoPage({ page: 1, size: 1000 });

      return res?.data?.records;
    },
    {
      refreshDeps: []
    }
  );
  const submit = useRequest(
    async ({ _type, ...values }) => {
      const query = {
        ...values,
        dutyUserName: userInfo?.data?.filter((item) => item.id === values?.dutyUserId)?.[0]
          ?.fullName,
        maintainUserName: userInfo?.data?.filter((item) => item.id === values?.maintainUserId)?.[0]
          ?.fullName,
        useUserName: userInfo?.data?.filter((item) => item.id === values?.useUserId)?.[0]?.fullName
      };

      if (args?.type === 'edit' && args.rowData) {
        query.id = args.rowData.id;
      }

      await (args?.type === 'edit' ? equInfoUpdate(query) : equInfoAdd(query));

      args?.onSuccess?.();
      setOpen(false);

      store.app?.message.success(args?.type === 'edit' ? '编辑成功' : '新增成功');
    },
    {
      manual: true
    }
  );

  useImperativeHandle(ref, () => {
    return {
      open: (arg) => {
        setArgs(arg);
        setOpen(true);

        setTimeout(() => {
          // 编辑回填数据
          if ((arg?.type === 'edit' || arg?.type === 'detail') && arg?.rowData) {
            // 回填数据
            form.setFieldsValue({
              ...arg.rowData
            });
          } else {
            form.resetFields();
          }
        });
      }
    };
  });

  const onFinish: FormProps['onFinish'] = async (values) => {
    return submit.runAsync(values);
  };

  const onCancel = () => {
    if (submit.loading) {
      store.app?.message.info('正在提交中，请稍后');

      return;
    }

    setOpen(false);
  };

  // 仅保存
  const onSave = () => {
    form.submit();
  };

  return (
    <Drawer
      title={
        {
          add: '新增设备台账',
          edit: '编辑设备台账',
          detail: '设备台账详情'
        }[args?.type as string]
      }
      extra={
        <>
          {args?.type !== 'detail' && (
            <Space>
              <Button
                type="primary"
                loading={submit.loading}
                disabled={submit.loading}
                onClick={onSave}
              >
                保存
              </Button>
              <Button onClick={onCancel} disabled={submit.loading}>
                取消
              </Button>
            </Space>
          )}
        </>
      }
      width="50%"
      open={open}
      onClose={onCancel}
    >
      <Form
        onFinish={onFinish}
        form={form}
        layout="horizontal"
        labelCol={{ span: 6 }}
        wrapperCol={{ span: 14 }}
        disabled={args?.type === 'detail'}
        requiredMark={args?.type !== 'detail'}
        variant={args?.type === 'detail' ? 'borderless' : undefined}
      >
        <Form.Item
          label="设备名称"
          name="equipmentName"
          rules={[
            {
              required: true,
              message: '请输入设备名称'
            }
          ]}
        >
          <Input placeholder="请输入设备名称" />
        </Form.Item>
        <Form.Item
          label="资产编号"
          name="equipmentCode"
          rules={[
            {
              required: true,
              message: '请输入资产编号'
            }
          ]}
        >
          <Input placeholder="请输入资产编号" />
        </Form.Item>
        <Form.Item
          label="规格型号"
          name="specification"
          rules={[
            {
              required: true,
              message: '请输入规格型号'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入规格型号" />
        </Form.Item>
        <ProFormSelect
          name="productionSite"
          label="生产站点"
          placeholder="请选择生产站点"
          rules={[{ required: true, message: '请选择生产站点' }]}
          request={async () => {
            return (store.dict['productionSite'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
        />
        <ProFormSelect
          name="processSection"
          label="工艺段"
          placeholder="请选择工艺段"
          rules={[{ required: true, message: '请选择工艺段' }]}
          request={async () => {
            return (store.dict['processSection'] || []).map((item) => ({
              value: item.dicValue,
              label: item.dicName
            }));
          }}
        />
        <Form.Item
          label="资产大类"
          name="equipmentType"
          rules={[
            {
              required: true,
              message: '请输入资产大类'
            }
          ]}
        >
          <Input placeholder="请输入资产大类" />
        </Form.Item>
        <Form.Item
          label="设备等级"
          name="equipmentLevel"
          rules={[
            {
              required: true,
              message: '请选择设备等级'
            }
          ]}
        >
          <Select
            style={{
              width: '100%'
            }}
            allowClear
            placeholder="请选择设备等级"
            options={[
              {
                label: '一般设备',
                value: '一般设备'
              },
              {
                label: '关重设备',
                value: '关重设备'
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="产家/供应商"
          name="equipmentManufacturer"
          rules={[
            {
              required: false,
              message: '请输入产家/供应商'
            }
          ]}
        >
          <Input placeholder="请输入产家/供应商" />
        </Form.Item>
        <Form.Item
          label="单位"
          name="unit"
          rules={[
            {
              required: false,
              message: '请输入单位'
            }
          ]}
        >
          <Input placeholder="请输入单位" />
        </Form.Item>
        <Form.Item
          label="数量"
          name="quantity"
          rules={[
            {
              required: true,
              message: '请输入数量'
            }
          ]}
        >
          <InputNumber style={{ width: '100%' }} placeholder="请输入数量" />
        </Form.Item>
        <Form.Item
          label="不含税单价(元)"
          name="priceExcludingTax"
          rules={[
            {
              required: false,
              message: '请输入不含税单价'
            }
          ]}
        >
          <InputNumber style={{ width: '100%' }} placeholder="请输入不含税单价" />
        </Form.Item>
        <Form.Item
          label="不含税金额(元)"
          name="amountExcludingTax"
          rules={[
            {
              required: false,
              message: '请输入不含税金额'
            }
          ]}
        >
          <InputNumber style={{ width: '100%' }} placeholder="请输入不含税金额" />
        </Form.Item>
        <Form.Item
          label="使用状态"
          name="useStatus"
          rules={[
            {
              required: false,
              message: '请选择使用状态'
            }
          ]}
        >
          <Select
            style={{ width: '100%' }}
            placeholder="请选择使用状态"
            options={[
              {
                label: '未使用',
                value: 1
              },
              {
                label: '已使用',
                value: 2
              },
              {
                label: '报废',
                value: 3
              }
            ]}
          />
        </Form.Item>
        <Form.Item
          label="使用部门"
          name="useDeptId"
          rules={[
            {
              required: true,
              message: '请选择使用部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择使用部门"
            allowClear
            // multiple
          />
        </Form.Item>
        <ProFormSelect
          name="useUserId"
          label="使用人员"
          placeholder="请选择使用人员"
          showSearch={true}
          dependencies={['useDeptId']}
          rules={[{ required: true, message: '请选择使用人员' }]}
          request={async ({ useDeptId }) => {
            if (!useDeptId) return [];
            const res = await orgUserInfoVoPage({
              page: 1,
              size: 1000,
              deptId: useDeptId
            });

            return (
              res?.data?.records?.map((item) => {
                return {
                  label: item?.fullName,
                  value: item?.id
                };
              }) || []
            );
          }}
        />
        <Form.Item
          label="管理部门"
          name="manageDeptId"
          rules={[
            {
              required: true,
              message: '请选择管理部门'
            }
          ]}
        >
          <TreeSelect
            treeData={tree.data}
            treeNodeFilterProp="title"
            showSearch
            placeholder="请选择管理部门"
            allowClear
            // multiple
          />
        </Form.Item>

        <Form.Item
          label="存放地点"
          name="storageLocation"
          rules={[
            {
              required: true,
              message: '请输入存放地点'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入存放地点" />
        </Form.Item>
        <Form.Item
          label="备注"
          name="remarks"
          rules={[
            {
              required: false,
              message: '请输入备注'
            }
          ]}
        >
          <Input.TextArea placeholder="请输入备注" />
        </Form.Item>
      </Form>
    </Drawer>
  );
};

export default forwardRef(Edit);
